package com.socialsoftware.MediaCommunication.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ServiceInfo;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.socialsoftware.MediaCommunication.activity.IncomingCallActivity;
import com.socialsoftware.MediaCommunication.model.CallMode;
import com.socialsoftware.MediaCommunication.model.MessageType;
import com.socialsoftware.MediaCommunication.utils.Constants;
import com.socialsoftware.R;
/**
 * Service for managing incoming calls and notifications
 */
public class CallService extends Service {
    private static final String TAG = "CallService";
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "call_channel";

    private MediaPlayer ringtonePlayer;
    private Vibrator vibrator;
    private PowerManager.WakeLock wakeLock;
    private String currentCaller;
    private String currentCallMode;
    private boolean isCallActive = false;
    private final IBinder binder = new CallServiceBinder();
    private String username;

    private final BroadcastReceiver callReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_INCOMING_CALL.equals(intent.getAction())) {
                String caller = intent.getStringExtra(Constants.EXTRA_CALLER_NAME);
                String mode = intent.getStringExtra(Constants.EXTRA_CALL_MODE);
                if (mode == null || mode.isEmpty()) {
                    Log.e(TAG, "收到没有指定通信模式的来电请求，默认使用音频模式");
                    mode = CallMode.AUDIO.getValue();
                }
                handleIncomingCall(caller, mode);
            } else if (Constants.ACTION_WEBSOCKET_MESSAGE.equals(intent.getAction())) {
                String type = intent.getStringExtra(Constants.EXTRA_MESSAGE_TYPE);
                if (MessageType.HANGUP.getValue().equals(type)) {
                    stopRinging();
                    cancelCallNotification();
                }
            }
        }
    };

    public class CallServiceBinder extends Binder {
        public CallService getService() {
            return CallService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        
        // Register for call events
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_INCOMING_CALL);
        filter.addAction(Constants.ACTION_WEBSOCKET_MESSAGE);
        LocalBroadcastManager.getInstance(this).registerReceiver(callReceiver, filter);
        
        // Create notification channel for Android O and above
        createNotificationChannel();
        
        // Initialize components
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                "demo:callWakelock");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.hasExtra("username")) {
            username = intent.getStringExtra("username");
            Log.d(TAG, "通话服务初始化，用户名: " + username);
        }
        
        // Start as a foreground service to avoid being killed
        // Use foreground service type flags for Android 13+
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(NOTIFICATION_ID, createServiceNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE);
        } else {
            startForeground(NOTIFICATION_ID, createServiceNotification());
        }
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Call Notifications",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("Notifications for incoming calls");
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private Notification createServiceNotification() {
        String contentText = "随时准备接听来电";
        if (username != null && !username.isEmpty()) {
            contentText = username + " 随时准备接听来电";
        }
        
        // Create a basic notification for the foreground service
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("通话服务运行中")
                .setContentText(contentText)
                .setSmallIcon(R.drawable.ic_call)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
    }

    private void handleIncomingCall(String caller, String mode) {
        if (isCallActive) {
            // Already in a call, ignore
            return;
        }
        
        currentCaller = caller;
        currentCallMode = mode;
        isCallActive = true;
        
        // Wake up the device
        if (wakeLock != null && !wakeLock.isHeld()) {
            wakeLock.acquire(60 * 1000L); // 60 seconds max
        }
        
        // Start ringing
        startRinging();
        
        // Show notification
        showIncomingCallNotification(caller, mode);
        
        // Start incoming call activity
        Intent incomingCallIntent = new Intent(this, IncomingCallActivity.class);
        incomingCallIntent.putExtra(Constants.EXTRA_CALLER_NAME, caller);
        incomingCallIntent.putExtra(Constants.EXTRA_CALL_MODE, mode);
        incomingCallIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(incomingCallIntent);
    }

    private void showIncomingCallNotification(String caller, String mode) {
        // Create intent for answering the call
        Intent answerIntent = new Intent(this, IncomingCallActivity.class);
        answerIntent.putExtra(Constants.EXTRA_CALLER_NAME, caller);
        answerIntent.putExtra(Constants.EXTRA_CALL_MODE, mode);
        answerIntent.putExtra(Constants.EXTRA_ANSWER_CALL, true);
        answerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent answerPendingIntent = PendingIntent.getActivity(
                this, 0, answerIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        
        // Create intent for rejecting the call
        Intent rejectIntent = new Intent(this, IncomingCallActivity.class);
        rejectIntent.putExtra(Constants.EXTRA_CALLER_NAME, caller);
        rejectIntent.putExtra(Constants.EXTRA_CALL_MODE, mode);
        rejectIntent.putExtra(Constants.EXTRA_REJECT_CALL, true);
        rejectIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent rejectPendingIntent = PendingIntent.getActivity(
                this, 1, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        
        // Create the notification
        String callType;
        if (CallMode.VIDEO.getValue().equals(mode)) {
            callType = "视频通话";
        } else if (CallMode.SCREEN.getValue().equals(mode)) {
            callType = "屏幕共享";
        } else {
            callType = "语音通话";
        }
        
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("来电: " + caller)
                .setContentText("收到" + callType + "请求")
                .setSmallIcon(R.drawable.ic_call)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_CALL)
                .setFullScreenIntent(answerPendingIntent, true)
                .addAction(R.drawable.ic_call_answer, "接听", answerPendingIntent)
                .addAction(R.drawable.ic_call_decline, "拒绝", rejectPendingIntent)
                .setAutoCancel(true)
                .setOngoing(true)
                .build();
        
        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID + 1, notification);
    }

    private void startRinging() {
        // Start playing ringtone
        if (ringtonePlayer == null) {
            ringtonePlayer = MediaPlayer.create(this, R.raw.incomingcall);
            ringtonePlayer.setLooping(true);
            ringtonePlayer.setAudioAttributes(new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build());
            ringtonePlayer.start();
        }
        
        // Start vibration
        if (vibrator != null) {
            long[] pattern = {0, 1000, 1000};
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createWaveform(pattern, 0));
            } else {
                vibrator.vibrate(pattern, 0);
            }
        }
    }

    public void stopRinging() {
        // Stop ringtone
        if (ringtonePlayer != null) {
            ringtonePlayer.stop();
            ringtonePlayer.release();
            ringtonePlayer = null;
        }
        
        // Stop vibration
        if (vibrator != null) {
            vibrator.cancel();
        }
        
        // Release wake lock
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
        }
        
        isCallActive = false;
        currentCaller = null;
        currentCallMode = null;
    }

    public void cancelCallNotification() {
        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_ID + 1);
    }

    @Override
    public void onDestroy() {
        stopRinging();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(callReceiver);
        super.onDestroy();
    }

    public String getUsername() {
        return username;
    }
} 